import { Component, OnInit } from '@angular/core';
import {TempManageService} from '../../../main/store-product/temp-manage/temp-manage-service';
import {StoreProductService} from '../store-product.service';
import {adSystemApiUrl, AliyunOssOutputUrl} from '../../../../config/api';
import {HttpService} from '../../../lib/service/http.service';
import {Router} from "@angular/router";
import {AbstractControl, FormArray, FormBuilder, FormGroup, Validators} from "@angular/forms";
import {GroupService} from "../../group/group.service";
import {NzMessageService} from "ng-zorro-antd";
import {DisplayService} from "../../display/display.service";
import {LocalStorageService} from "../../../lib/service/local-storage.service";
import * as moment from 'moment';

@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss'],
  providers: [TempManageService,GroupService,StoreProductService]
})
export class AddComponent implements OnInit {
  aliyunOssOutputUrl = AliyunOssOutputUrl;
  current = 0;
  templateList = [];
  total:number;
  page = 1;
  pageSize = 8;
  templateId;
  validateForm: FormGroup;
  title:string;
  created:string;
  keyWordList = [];
  keyWord = {};
  extend_keyword = [];
  haslen = false;
  _date = new Date().setHours(new Date().getHours()+1);
  radioValue = 'timing';
  activeTypeText = '首页';
  sliderWidth;
  toggleCollapsed;
  type = 0;
  stage = 2;
  status1 = 1;



  options = [
    { value: 'pages/index/index', label: '首页' },
    { value: 'pages/product-list/product-list', label: '商品列表' },
    { value: 'pages/product/product', label: '商品详情' },
    { value: 'pages/group-product/group-product', label: '拼团详情' },
    { value: 'pages/group-buy-list/group-buy-list', label: '拼团列表' },
    { value: 'pages/index/index?card_coupons_uuid=', label: '卡券' }
    ];

  selectedOption = this.options[0];

  activeType = 0;
  sending = false;


  /* 商品弹窗 */
  goodsModalVisible = false;
  goodsList = [];
  groupList = [];
  selectedGroup;
  keyword;
  currentClickGoods = {};
  checkedGoodsInfo = {};
  goodsPage = 1;
  goodsPageSize = 5;
  goodsTotal;
  status = '上架';
  loading = false;
  currentGoodsPrice = 0;
  activity_goods_prize;
  typeText = {
    1: { text: '普通拼团', color: 'rgb(299,112,23)' },
    2: { text: '拉新拼团', color: 'rgb(299,112,23)' },
    3: { text: '抽奖拼团', color: 'rgb(299,112,23)' },
    4: { text: '团长免单', color: 'rgb(299,112,23)' },
  };
  send_mode = 3;
  cachePage;

  //卡券弹窗
  couponModalVisible = false;
  couponList = [];
  couponLoading = false;
  couponsTotal;
  currentClickCoupon = {};
  checkedCouponInfo = {};
  couponKeyWord = '';
  couponClickIndex;


  //活动弹窗
  activityModalVisible = false;
  activityList = [];
  activityLoading = false;
  activitiesTotal;
  currentClickActivity = {};
  checkedActivityInfo = {};
  activityClickIndex;

  goodsKeyword;
  couponsKeyword;
  activityKeyword;



  checkOptionsOne = [
    { label: '关键词放大', value: '1' },
    { label: '标红', value: '#ef3318' },
  ];


  index = 'First-content';

  toggleSendMode(e) {
    console.log(e);
  }

  formatDate() {
    return moment(this._date).format('YYYY-MM-DD HH:mm:ss');
  }


  pre(): void {
    this.current -= 1;
    this.changeContent();
  }

  next(): void {
    this.current += 1;
    this.changeContent();
  }

  done(): void {
    console.log('done');
  }

  changeContent(): void {
    switch (this.current) {
      case 0: {
        this.index = '-----';
        break;
      }
      case 1: {
        this.index = 'Second-content';
        break;
      }
      case 2: {
        this.index = 'third-content';
        break;
      }
      default: {
        this.index = 'error';
      }
    }
  }
  constructor(private httpService: HttpService,
              private router: Router,
              private fb: FormBuilder,
              private groupService: GroupService,
              private _message: NzMessageService,
              private displayService: DisplayService,
              private localStorageService: LocalStorageService,
              private storeProductService: StoreProductService
  ) {
    this.validateForm = this.fb.group({
      'wx_id': ['',Validators.required],
      'appid': ['',Validators.required],
      'applet_id': ['',Validators.required],
      'applet_uuid': ['',Validators.required],
      'wx_template_message_id': ['',Validators.required],
      'page': ['pages/index/index',Validators.required],
      'emphasis_keyword_color': ["#000",Validators.required],
      'emphasis_keyword':['0',Validators.required],
      'send_mode': [this.send_mode,Validators.required],
      // 'job_content': ['',Validators.required]
    })
  }


  newArray = (len) => {
    const result = [];
    for (let i = 0; i < len; i++) {
      result.push(i);
    }
    return result;
  };


  _disabledStartDate = (startValue) => {
    const now = new Date();
    now.setHours(0, 0, 0, 0);
    console.log(startValue);
    return (startValue.getTime() <= Date.now());
  };



  getFormControl(name) {
    return this.validateForm.controls[name];
  }

  ngOnInit() {
    this.getOwnerTemplateList();
  }
  // 获取拥有的模板消息列表
  getOwnerTemplateList(e?) {
    if(e) {
      this.page = e;
    }
    const url = `${adSystemApiUrl}/v1/member/wechat/applet_message_template_list?page=${this.page}&pageSize=${this.pageSize}`;
    return this.httpService.httpGetAuth(url).subscribe(
      res => {
        this.templateList = res.data.data;
        this.total = this.templateList.length;
        console.log('-temp-', this.templateList);
        if (!!this.templateList) {
          this.templateList.every((val, idx, array) => {
            if (!!val.extend) {
              val.extend.key_list = JSON.parse(val.extend.key_list);
              val.extend.keyword_list = JSON.parse(val.extend.keyword_list);
              return true;
            } else {
              return false;
            }
          });
        }
      }
    );
  }

  chooseTemplate(id) {
    this.templateId = id;
  }


  goModule(e,data) {
    e.stopPropagation();
    this.current = 1;

    console.log(data);
    let dataset = ['wx_id','appid','applet_uuid','applet_id','wx_template_message_id'];
    dataset.map((e,i) => {
      this.validateForm.controls[e].setValue(data[e]);
    });
    // this.validateForm.controls['wx_id'].setValue(data['wx_id']);
    // this.validateForm.controls['appid'].setValue(data['appid']);
    // this.validateForm.controls['applet_uuid'].setValue(data['applet_uuid']);
    // this.validateForm.controls['applet_id'].setValue(data['applet_id']);
    // this.validateForm.controls['wx_template_message_id'].setValue(data['wx_template_message_id']);
    this.title = data.title;
    this.created = data.created_at;
    this.keyWordList = data['extend']['keyword_list'];
    for(let i = 10; i>0; i--) {
      this.validateForm.removeControl('keyword' + i);
    }
    data['extend']['key_list'].map((e,i) => {
      this.keyWord[`keyword ${i+1}`] = '';
      this.validateForm.addControl('keyword' + (i+1),this.fb.control('',[Validators.required]));
    });
    this.extend_keyword = data['extend']['key_list'];
    this.haslen = Object.keys(this.keyWord).length > 0;
    this.activeType = 0;
    this.activeTypeText = '首页';
    this.selectedOption = this.options[0];
    console.log(this.validateForm.value);
    this.changeContent();
  }


  goSendStep() {

    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
    }
    console.log(this.validateForm.value);
    if(this.validateForm.valid) {
      this.current = 2;
      this.changeContent();
    }
  }

  goBack(step) {
    this.current = step;
    this.changeContent();
  }


  goConfirmStep() {
    this.current = 3;
    this.changeContent();
  }

  goprevStep() {
    this.current = 2;
    this.changeContent();
  }



// { value: 'pages/index/index', label: '首页' },
// { value: 'pages/product-list/product-list', label: '商品列表' },
// { value: 'pages/product/product', label: '商品详情' },
// { value: 'pages/group-product/group-product', label: '拼团详情' },
// { value: 'pages/group-buy-list/group-buy-list', label: '拼团列表' },
// { value: 'pages/index/index?card_coupons_uuid=', label: '卡券' }
  /*活动弹窗逻辑*/
  // 获取活动列表
  getActivityList() {
    this.activityLoading = true;
    this.displayService.getActivityList(this.page, this.pageSize, this.keyword, this.type, this.stage, this.status1).subscribe(res => {
      if (res.code === 2000) {
        this.activityList = res.data.data;
        this.activityList.map((e, i) => {
          e['flexable'] = false;
        })
        this.activitiesTotal = res.data.total;
        this.activityLoading = false;
      }
    })
  }
  //搜索活动
  searchActivity() {
    this.page = 1;
    this.pageSize = 5;
    this.getActivityList();
  }
  //打开活动模态框
  addActivity() {
    this.keyword = '';
    this.page = 1;
    this.pageSize = 5;
    this.currentClickActivity = this.checkedActivityInfo;
    this.activityModalVisible = true;
    this.getActivityList();
  }

  //重置活动
  resetActivity() {
    this.keyword = '';
    this.page = 1;
    this.getActivityList();
  }

  //关闭活动模态框
  closeActivityModal() {
    this.activityModalVisible = false;
    this.activityList.map((e, i) => {
      e['flexable'] = false;
    });
  }
  //确认活动模态框
  confirmCheckedActivity() {
    if (!Object.keys(this.currentClickActivity).length) {
      this._message.create('error', '请选择活动');
      return;
    }
    this.checkedActivityInfo = this.currentClickActivity;
    this.checkedActivityInfo['flexable'] = false;
    this.checkedActivityInfo['type'] = this.typeText[this.currentClickActivity['activity_goods'][0]['type']];
    this.validateForm.controls['page'].setValue('pages/group-product/group-product?id=' + this.checkedActivityInfo['id']);
    this.activityList.map((e, i) => {
      e['flexable'] = false;
    });
    this.activityModalVisible = false;
  }
  //获取活动商品列表
  getActivityGoodsList(activityId, activityGoodsId) {
    this.displayService.getActivityGoodsList(activityId, activityGoodsId).subscribe(res => {
      if (res.code === 2000) {
        this.activityList[this.activityClickIndex]['goodsDetail'] = res.data;
      }
    })
  }
  //查看活动商品
  toggleFlexable(i) {
    this.activityClickIndex = i;
    let target = this.activityList[i];
    target['flexable'] = !target['flexable'];
    if (target['flexable']) {
      let activityId = target['id'], activity_goods_id = target['activity_goods'][0]['id'];
      this.getActivityGoodsList(activityId, activity_goods_id);
    }
  }
  //切换checked查看商品
  toggleViewActivityGoods() {
    this.checkedActivityInfo['flexable'] = !this.checkedActivityInfo['flexable'];
  }

  toggleType(e) {
   let value = e.value;
    if(this.cachePage != value) {
      this.validateForm.controls['page'].reset();
      // this.validateForm.controls['page'].setValue('');
      this.currentClickCoupon = {};
      this.checkedCouponInfo = {};
      this.currentClickActivity = {};
      this.checkedActivityInfo = {};
      this.currentClickGoods = {};
      this.checkedGoodsInfo = {};
    }
   if(value == 'pages/group-buy-list/group-buy-list' || value == 'pages/index/index' || value == 'pages/product-list/product-list') {
     this.validateForm.controls['page'].setValue(value);
     this.activeType = 0;
     this.activeTypeText = e.label;
   }

   switch (value) {
     case 'pages/product/product':
       this.activeType = 3;
       break;
     case 'pages/group-product/group-product':
       this.activeType = 4;
       break;
     case 'pages/index/index?card_coupons_uuid=':
       this.activeType = 6;
       break;
   }
   this.cachePage = value;
  }

  currentClick(data) {
    this.currentClickActivity = data;
  }

  checkOptions(data) {
    data.map((e,i) => {
      if(e.label === '关键词放大') {
        this.validateForm.controls['emphasis_keyword'].setValue(e.checked ? '1' : '0');
      }
      if(e.label === '标红'){
        this.validateForm.controls['emphasis_keyword_color'].setValue(e.checked ? '#ef3318' : '#000');
      }
    });
  }

  /*
  *
  * 商品弹窗*/


  /* 商品弹窗逻辑 */
  // 获取商品列表
  getGoodsList() {
    this.loading = true;
    this.getGroupList();
    this.pageSize = 5;
    this.groupService.getGoodsList(this.page, this.pageSize, this.selectedGroup, this.keyword, this.status).subscribe(res => {
      if (res.code === 2000) {
        this.total = res.data.total;
        const goodsList = res.data.data;
        const goodsId = [];
        goodsList.forEach(item => {
          goodsId.push(item.id);
        });
        this.groupService.getbindListAll('[' + goodsId.join(',') + ']').subscribe(rs => {
          if (rs.code === 2000) {
            const goodsjson = {};
            rs.data.forEach(item => {
              if (!goodsjson[item.goods_id]) {
                goodsjson[item.goods_id] = [item.name];
              } else {
                goodsjson[item.goods_id].push(item.name);
              }
            });
            goodsList.forEach(item => {
              if (item.goods_number) {
                item.goods_number = item.goods_number.split('|');
              }
              item.goods_category = goodsjson[item.id];
            });
          }
          this.goodsList = goodsList;
          this.loading = false;
        });
      } else {
        this._message.create('error', res.message);
      }
      this.loading = false;
    });
  }
  // 搜索商品
  searchGoods() {
    this.page = 1;
    this.getGoodsList();
  }
  //重置商品
  resetGoods() {
    this.page = 1;
    this.keyWord = '';
    this.getGoodsList();
  }

  // 添加商品
  addGoods() {
    this.page = 1;
    this.keyword = '';
    this.currentClickGoods = JSON.parse(JSON.stringify(this.currentClickGoods));
    this.goodsModalVisible = true;
    this.getGoodsList();
  }
  // 关闭添加商品弹窗
  closeModal() {
    this.currentClickGoods = JSON.parse(JSON.stringify(this.checkedGoodsInfo));
    this.goodsModalVisible = false;
  }
  // 确认选择商品
  confirmCheckedGoods() {
    if (!Object.keys(this.currentClickGoods).length) {
      this._message.create('error', '请选择商品');
      return;
    }
    this.checkedGoodsInfo = JSON.parse(JSON.stringify(this.currentClickGoods));
    this.validateForm.controls['page'].setValue('pages/product/product?id='+ this.checkedGoodsInfo['id']);
    // 获取选择商品的sku
    this.groupService.getGoodsSkuList(this.currentClickGoods['id'], 100).subscribe(res => {
      if (res.code === 2000) {
        const sku = res.data.data;
        const activity_goods_prize = [];
        sku.map((val, idx) => {
          val.checked = true;
          const sku_item = { 'sku_id': val.id, 'number': val.in_stock };
          activity_goods_prize.push(sku_item);
        });
        this.activity_goods_prize = activity_goods_prize;
        this.checkedGoodsInfo['sku'] = sku;
        this.goodsModalVisible = false;
      } else {
        this._message.create('error', res.message);
      }
    });
  }



  /*卡券弹窗逻辑*/
  addCoupon() {
    this.page = 1;
    this.pageSize = 5;
    this.keyword = '';
    this.couponModalVisible = true;
    this.getCouponList();
  }

  //重置卡券
  resetCoupon() {
    this.page = 1;
    this.keyword = '';
    this.getCouponList();
  }


  //获取卡券列表
  getCouponList() {
    this.couponLoading = true;
    this.displayService.getCouponList(this.page, this.pageSize, this.keyword).subscribe(res => {
      if (res.code === 2000) {
        this.couponList = res.data.data;
        this.couponsTotal = res.data.total;
        this.couponLoading = false;
      }
    });
  }
  //搜索卡券
  searchCoupon() {
    this.page = 1;
    this.getCouponList();
  }
  //关闭卡券模态框
  closeCouponModal() {
    this.couponModalVisible = false;
    this.currentClickCoupon = this.checkedCouponInfo;
  }
  //确认卡券模态框信息
  confirmCheckedCoupon() {
    if(!Object.keys(this.currentClickCoupon).length) {
      this._message.create('error', '请选择卡券');
      return;
    }
    this.checkedCouponInfo = this.currentClickCoupon;
    this.validateForm.controls['page'].setValue('pages/index/index?card_coupons_uuid=' + this.checkedCouponInfo['card_coupons_uuid']);
    this.couponModalVisible = false;
  }

  // 获取店铺商品类型列表
  getGroupList() {
    this.groupService.getGroupList().subscribe(res => {
      this.groupList = res.data.data;
    });
  }

  _submitForm() {
    if(this.validateForm.valid) {
      /*
* {"emphasis_keyword":"0",
* "emphasis_keyword_color":"#ef3318",
* "keyword":{"keyword1":"字符串一","keyword2":"字符串二"},
* "page":"page/page/goodsdetail?id=119&batch_no=bas_kdkdkaj"
* }
* */

      const data = {};
      const value = this.validateForm.value;
      data['wx_template_message_id'] = value['wx_template_message_id'];
      data['wx_id'] = value['wx_id'];
      data['applet_id'] = value['applet_id'];
      data['appid'] = value['appid'];
      data['send_mode'] = value['send_mode'];
      data['job_content'] = {};
      data['job_content']['keyword'] = {};
      data['job_content']['emphasis_keyword'] = value['emphasis_keyword'];
      data['job_content']['page'] = value['page'];
      data['job_content']['emphasis_keyword_color'] = value['emphasis_keyword_color'];
      for(let k in value) {
        if(/^keyword\d{1,2}$/g.test(k)) {
          data['job_content']['keyword'][k] = value[k];
        }
      }
      data['job_content'] = JSON.stringify(data['job_content']);
      if(this.radioValue === 'timing') {
        if(moment(new Date(this._date)).diff(moment(new Date())) > 300000) {
          data['send_time'] = moment(this._date).format('YYYY-MM-DD HH:mm:ss');
          } else {
          data['send_time'] = moment().add(5, "minute").format('YYYY-MM-DD HH:mm:ss')
          }
        } else {
          data['send_time'] = moment().add(5, "minute").format('YYYY-MM-DD HH:mm:ss')
        }
      this.sending = true;
      this.storeProductService.addJob(data).subscribe(res => {
        if(res.code === 2000) {
          this._message.create('success','添加成功');
          this.sending = false;
          this.current = 4;
          this.changeContent();
        } else {
          this._message.create('error',res.message);
        }
      })
      }
  }

  goList() {
    this.router.navigate(['member/store-product/list']);
  }
}
